from flask import request, jsonify, json, Blueprint
from flask_restful import Resource, Api
from common.utils.get_data import get_data, _get_data
from common.utils.myredis import myredis
from second_flask.methods import db1
from flask import redirect

carts_bp = Blueprint('carts_bp', __name__)


@carts_bp.route('/addcarts', methods=['POST', 'GET'])
def add_carts():
    if request.method == 'POST':
        user_id = int(get_data()['user_id'])
        goods_id = int(get_data()['goods_id'])
        count = int(get_data()['count'])
        type = int(get_data()['type'])
        buykey = "buygoodskey"
        goods = myredis.hget(buykey, goods_id)
        if not goods:
            sql = "select goods_name,price,img from goods where id=%d" % (int(goods_id))
            good = db1.find(sql)
            if good:
                myredis.hsetnx(buykey, goods_id, json.dumps(good))
        if type == 2:
            pass
            # count = '-' + str(count)
        key = 'usercart%d' % (user_id)
        v = myredis.hget(key, goods_id)
        if v:
            myredis.hash_jia_jian(key, goods_id, count)
        else:
            myredis.hset(key, goods_id, count)
            myredis.set_add('userchecked%d' % user_id, goods_id)
        return jsonify({'code': 200})
    else:
        user_id = int(_get_data()['user_id'])
        key = 'usercart%d' % (user_id)
        carts = myredis.hgetall(key)
        print('carts>>>>', carts)
        list = []
        buykey = 'buygoodskey'
        total = 0
        for k, v in carts.items():
            dict = {'id': int(k.decode()), 'count': int(v.decode())}
            goods = myredis.hget(buykey, k.decode())
            dict2 = json.loads(goods)
            dict.update(dict2)
            list.append(dict)
            total += float(v.decode()) * float(dict2['price'])
        checked = myredis.set_getall('userchecked%d' % (user_id))
        clist = []
        if checked:
            for i in checked:
                clist.append(i.decode())
                print('clist>>>', clist)
        return jsonify({'code': 200, 'carts': list, 'total': total, 'clist': clist})


@carts_bp.route('/usercheck', methods=['POST'])
def usercheck():
    ids = get_data()['ids']
    user_id = get_data()['user_id']
    myredis.set_del('userchecked%d' % (user_id))
    if len(ids) > 0:
        for i in ids:
            myredis.set_add('userchecked%d' % (user_id), i)
    return jsonify({'code': 200})


from common.utils.common import get_ali_object


@carts_bp.route('/testabc')
def testabc():
    alipay = get_ali_object()
    # 生成支付的url
    id = _get_data()['id']
    sql = "select goods_name,price,count from orders_detail where order_no='%s'" % (id)
    list = db1.find_all(sql)
    total = 0
    for i in list:
        price = i['price']
        count = i['count']
        total += price * count
    query_params = alipay.direct_pay(
        subject="test",  # 商品简单描述
        out_trade_no=id,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=total,  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({'code': 200, 'pay_url': pay_url})


import random
import time
from datetime import datetime


@carts_bp.route('/addorders', methods=['POST'])
def addorders():
    result = get_data()['result']
    user_id = get_data()['user_id']
    print('result>>>>', result)
    buykey = 'buygoodskey'
    key = 'usercart%d' % int(user_id)
    total = 0
    code = str(user_id) + str(random.randint(10000, 99999)) + str(int(time.time()))
    date = datetime.now()
    score = int(time.time()) + 20
    try:
        for i in result:
            goods = json.loads(myredis.hget(buykey, i))
            print('goods>>>>', goods, i)
            price = goods['price']
            # print('price>>>>', price)
            # print('dsadsa',myredis.hget(key, i))
            goods_count = json.loads(myredis.hget(key, i))
            # print('111111', goods_count)
            img = goods['img']
            total += price * goods_count
            goods_name = goods['goods_name']
            sql1 = "insert into orders_detail(order_no,goods_id,img,price,count,date,goods_name) values('%s',%d,'%s','%s',%d,'%s','%s')" % (
                code, int(i), img, price, int(goods_count), date, goods_name)
            db1.update(sql1)
            print(sql1)
            # print(code)
            sql = "insert into orders(order_no, total, date) values('%s','%s','%s')" % (code, total, date)
            db1.update(sql)
            db1.commit()
    except Exception as e:
        db1.rollback()
        print(">>>>", e)
    # myredis.l_push('order_no_list', code)
    myredis.zset_add('order_no_list', score, code)
    return jsonify({'code': 200, 'order_no': code})


@carts_bp.route('/getorders', methods=['GET'])
def getorders():
    sql = "select * from orders"
    order_list = db1.find_all(sql)
    return jsonify({'code': 200, 'order_list': order_list})


@carts_bp.route('/orders_detail', methods=['GET'])
def orders_detail():
    id = _get_data()['id']
    print('id>>>>', id)
    sql = "select * from orders_detail where order_no='%s'" % (id)
    orders_list = db1.find_all(sql)
    return jsonify({'code': 200, 'orders_list': orders_list})


@carts_bp.route('/callback')
def callback():
    data = request.args
    order = data['trade_no']
    order_no = data['out_trade_no']
    print('order', order)
    print('order_no', order_no)
    sql = "update orders set status=1,serial_number={} where order_no={}".format(order, order_no)
    print('sql', sql)
    db1.update(sql)
    db1.commit()
    sqk = "select count,goods_id from orders_detail where order_no={}".format(order_no)
    print('>>>>>>', sqk)
    list = db1.find_all(sqk)
    for i in list:
        count = i['count']
        goods_id = i['goods_id']
        sql = "select stock from goods where id=%d" % (int(goods_id))
        stock_list = db1.find_all(sql)
        print('5555555555555555555555555555555555555')
        for k in stock_list:
            stock = k['stock']
            stock -= count
            sql = "update goods set stock=%d" % (int(stock))
            db1.update(sql)
            db1.commit()
            print('33333333333333333333333333333333333')
        key = 'usercart%d' % int(2)
        myredis.h_del(key, goods_id)
        print('6666666666666666666666666')
        # myredis.zset_del('order_no_list',order_no)
    return redirect('http://127.0.0.1:8080/carts')
